package com.njlime.member.controller.app;

import com.alibaba.fastjson.JSONObject;
import com.njlime.cms.service.app.AppInformationService;
import com.njlime.core.base.controller.BaseAppController;
import com.njlime.core.exception.BusinessException;
import com.njlime.core.exception.ExceptionState;
import com.njlime.core.helper.GlobalValue;
import com.njlime.core.helper.PageBean;
import com.njlime.core.helper.dic.DictionaryHelper;
import com.njlime.core.utils.HttpUtils;
import com.njlime.core.utils.StringUtil;
import com.njlime.core.web.AppWxInterceptor;
import com.njlime.member.entiies.*;
import com.njlime.member.service.app.*;
import com.njlime.sys.entities.ConfigItem;
import com.njlime.sys.service.ConfigService;
import com.njlime.sys.util.NoteSendUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Dean on 2017/10/10.
 */
@Controller
@RequestMapping(value = "/app/member")
public class AppMemberController extends BaseAppController {

    private Logger logger = Logger.getLogger(AppMemberController.class);
    @Resource
    private AppMemberService appMemberService;
    @Resource
    private AppMemberCommentService appMemberCommentService;
    @Resource
    private AppMemberNoticeService appMemberNoticeService;
    @Resource
    private ConfigService configService;
    @Resource
    private AppMemberCollectionService appMemberCollectionService;
    @Resource
    private AppInformationService appInformationService;
    @Resource
    private AppMemberTrackService appMemberTrackService;
    @Resource
    private AppMemberFocusService appMemberFocusService;

    /**
     * 用户注册
     */
    @ResponseBody
    @RequestMapping(value = "/register")
    public String register(HttpServletRequest request, TMember member, String verifyCode) {
        logger.info("/app/member/register");
        try {
            String noteCode = (String) request.getSession().getAttribute("noteCode");
            String noteCodeMobile = (String) request.getSession().getAttribute("noteCodeMobile");
            if (noteCode == null || ("").equals(noteCode)) {
                return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "短信验证码错误");
            } else {
                if (noteCode.equals(verifyCode) && member.getMobile().equals(noteCodeMobile)) {
                    Integer unit_id = (Integer) request.getSession().getAttribute(AppWxInterceptor.WX_USER_UNIT_ID);
                    member.setUnit_id(unit_id);
                    Map<String, Object> map = appMemberService.getUserByMobile(member.getMobile(), unit_id);
                    if (map != null) {
                        if (map.get("mobile") != null && map.get("mobile").toString().equals(member.getMobile())) {
                            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "该手机号码已经注册");
                        }
                    }
                    member.setId(null);
                    member.setPassword(StringUtil.MD5(member.getPassword()));
                    member.setName((member.getMobile().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2")));
                    member.setNick_name((member.getMobile().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2")));
                    member.setHead_url("app/images/defaultHead.png");
                    member = appMemberService.save(member);
                    addSession(member);
                } else {
                    return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "短信验证码错误");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "保存失败");
        }
        return toJsonSuccessData();

    }

    @ResponseBody
    @RequestMapping(value = "/checkLogin")
    public String checkLogin(HttpServletRequest request) {
        logger.info("app/member/checkLogin");
        try {
            Integer uid = (Integer) request.getSession().getAttribute(AppWxInterceptor.WX_USER_ID);
            if (uid == null) {
                return toJsonErrorData(ExceptionState.SESSION_EXCEPTION, "用户未登录");
            }
            return toJsonSuccessData();
        } catch (Exception e) {
            e.printStackTrace();
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "系统繁忙");
        }
    }

    /**
     * 检测手机号可用性
     * @param request
     * @param mobile
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/checkMobile")
    public String checkMobile(HttpServletRequest request, String mobile) {
        Integer unit_id = (Integer) request.getSession().getAttribute(AppWxInterceptor.WX_USER_UNIT_ID);
        Map<String, Object> map = appMemberService.getUserByMobile(mobile, unit_id);
        if (map != null) {
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION,"手机号已存在");
        }
        return toJsonSuccessData();
    }


    /**
     * 用户登录
     */
    @RequestMapping(value = "/login")
    @ResponseBody
    public String login(HttpServletRequest request ,String mobile, String password){
        logger.info("/app/member/login");
        try {
            Integer unit_id = (Integer) request.getSession().getAttribute(AppWxInterceptor.WX_USER_UNIT_ID);
            Map<String,Object> map =  appMemberService.getUserByMobile(mobile,unit_id);
            if(map== null){
                return toJsonErrorData(ExceptionState.SESSION_EXCEPTION, "用户不存在");
            }
            if(!StringUtil.MD5(password).equals(map.get("password"))){
                return toJsonErrorData(ExceptionState.SESSION_EXCEPTION, "用户名密码不匹配");
            }
            Integer id = Integer.valueOf(map.get("id").toString());
            appMemberService.updateVipUpdateTime(id);
            addSession(appMemberService.findOne(id));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toJsonSuccessData();
    }


    /**
     * 微信一键登录
     */
    @RequestMapping(value = "/loginWechat")
    public String loginWechat(RedirectAttributes redirectAttributes, HttpServletRequest request, HttpServletResponse response, String url, Integer loginFlag, String params){
        logger.info("/app/member/loginWechat");
        String openId = (String)request.getSession().getAttribute(AppWxInterceptor.WX_USER_OPENID);
        //String openId = "oAnDS0rQ5lFN-KVlPhcnM9g8X4tM";
        Integer unit_id = (Integer) request.getSession().getAttribute(AppWxInterceptor.WX_USER_UNIT_ID);
        Map<String, Object> vip;
        try {
            vip = appMemberService.getWechatMember(openId, unit_id);
        }catch (Exception e){
            logger.info("未订阅");
            redirectAttributes.addAttribute("pv","subscribe");
            try {
                String msg = new String(Base64.encodeBase64("您还没有订阅公众号哦~".getBytes("utf8")));
                redirectAttributes.addAttribute("msg", msg);
            } catch (Exception ee) {
                logger.info("加密错误");
            }
            return "redirect:/app/page";
        }
        Object mobile = vip.get("mobile");
        Integer id = Integer.valueOf(vip.get("id").toString());
        try {
            url = URLDecoder.decode(url, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            redirectAttributes.addAttribute("pv","mine");
            logger.info("url错误返回");
            return "redirect:/app/page";
        }
        if(mobile==null || "".equals(mobile.toString())){
            redirectAttributes.addFlashAttribute("member_id", id);
            redirectAttributes.addFlashAttribute("needMobile", GlobalValue.YES);
        }else{
            appMemberService.updateVipUpdateTime(id);
            addSession(appMemberService.findOne(id));
        }
        if(url.contains("?")){
            String[] urlStr = url.split("\\?");
            String[] paramsArr = urlStr[1].split("&");
            if(!urlStr[1].contains("pv=")){
                String pv= urlStr[0].substring(urlStr[0].indexOf("app/page/") + 8,urlStr[0].length());
                redirectAttributes.addAttribute("pv",pv);
            }
            for(int i = 0;i < paramsArr.length; i++){
                String[] param = paramsArr[i].split("=");
                redirectAttributes.addAttribute(param[0],param[1]);
            }
            redirectAttributes.addAttribute("token", params.hashCode());
            redirectAttributes.addFlashAttribute("loginFlag",loginFlag);
            redirectAttributes.addFlashAttribute("params",params);
        }
        logger.info("正常返回");
        return "redirect:/app/page";
    }

    /**
     * 注销登录
     */
    @RequestMapping(value = "/logout")
    @ResponseBody
    public String logout(HttpServletRequest request){
        logger.info("/app/member/logout");
        try {
            clearSession();
            return toJsonSuccessData();
        } catch (Exception e) {
            e.printStackTrace();
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "系统繁忙");
        }

    }

    /**
     * 绑定手机号
     */
    @RequestMapping(value = "/bindMobile")
    @ResponseBody
    public String bindMobile(HttpServletRequest request ,String mobile, String verifyCode,Integer id){
        logger.info("/app/member/bindMobile");
        try {
            String noteCode = (String) request.getSession().getAttribute("noteCode");
            String noteCodeMobile = (String) request.getSession().getAttribute("noteCodeMobile");
            if (noteCode == null || ("").equals(noteCode)) {
                return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "短信验证码错误");
            } else {
                if (noteCode.equals(verifyCode) && mobile.equals(noteCodeMobile)) {
                    Integer unit_id = (Integer) request.getSession().getAttribute(AppWxInterceptor.WX_USER_UNIT_ID);
                    Map<String, Object> map = appMemberService.getUserByMobile(mobile, unit_id);
                    if (map != null) {
                        if (map.get("mobile") != null && map.get("mobile").toString().equals(mobile)) {
                            TMember member = appMemberService.findOne(Integer.valueOf(map.get("id").toString()));
                            TMember newMember = appMemberService.findOne(id);
                            appMemberService.bindMember(member,newMember);
                            addSession(member);
                        }
                    }else{
                        appMemberService.updateMobile(id,mobile);
                        addSession(appMemberService.findOne(id));
                    }
                    return toJsonSuccessData();
                } else {
                    return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "短信验证码错误");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "系统错误");
        }
    }

    /**
     * 绑定标签
     */
    @RequestMapping(value = "/selectTags")
    @ResponseBody
    public String selectTags(HttpServletRequest request ,String tags){
        logger.info("/wcLogin/selectTags");
        try {
            Integer id = (Integer)request.getSession().getAttribute(AppWxInterceptor.WX_USER_ID) ;
            if(id==null){
                return toJsonErrorData(ExceptionState.SESSION_EXCEPTION,"请登录后重试");
            }
            appMemberService.updateTags(id,tags);
            return toJsonSuccessData();
        } catch (Exception e) {
            e.printStackTrace();
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "系统错误");
        }
    }



    /**
     * 个人设置，返回个人信息
     */
    @ResponseBody
    @RequestMapping(value = "/info")
    public String userInfo(HttpServletRequest request) {
        logger.info("app/member/info");
        try {
            Integer uid = (Integer) request.getSession().getAttribute(AppWxInterceptor.WX_USER_ID);
            if (uid == null) {
                return toJsonErrorData(ExceptionState.SESSION_EXCEPTION, "请登录后设置个人信息");
            }
            Map<String, Object> member = appMemberService.getMemberById(uid);
            if (member != null) {
                return toJsonSuccessData(member);
            } else {
                return toJsonErrorData(ExceptionState.SESSION_EXCEPTION, "请登录后设置个人信息");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "查找出错");
        }
    }

    /**
     * 足迹接口
     */
    @ResponseBody
    @RequestMapping(value = "/plant")
    public String plant(HttpServletRequest request, String verifyCode) {
        logger.info("app/member/plant");
        try {
            Integer uid = (Integer) request.getSession().getAttribute(AppWxInterceptor.WX_USER_ID);
            Integer unit_id = (Integer) request.getSession().getAttribute(AppWxInterceptor.WX_USER_UNIT_ID);
            if (uid == null) {
                return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "请先登录");
            }
            Map<String, Object> member = appMemberService.getMemberById(uid);
            if (member != null) {
                Map<String, Object> result = new HashMap<>();
                Integer last = Integer.parseInt(member.get("level_before").toString());
                if (last == 0) {
                    last = 1;
                }
                result.put("lastLevel", last);
                result.put("level", member.get("level_now"));
                result.put("nickName", member.get("name"));
                result.put("readNo", member.get("read_count"));
                ConfigItem configItem = configService.getByName("member_upgrade_condition", unit_id);
                result.put("levelNo", configItem.getConfig_value());
                return toJsonSuccessData(result);
            } else {
                return toJsonErrorData(ExceptionState.SESSION_EXCEPTION, "请先登录");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "查找出错");
        }
    }

    /**
     * 更新头像
     */
    @ResponseBody
    @RequestMapping(value = "/headIconEdit")
    public String headIconEdit(HttpServletRequest request, MultipartFile headIconFile) {
        logger.info("app/member/headIconEdit");
        try {
            Integer sysId = (Integer) request.getSession().getAttribute(AppWxInterceptor.WX_USER_ID);
            if (sysId == null) {
                return toJsonErrorData(ExceptionState.SESSION_EXCEPTION, "请登录后设置个人信息");
            }
            //String filePath = FileUpload.fileUp(headIconFile, request);
            CommonsMultipartFile cFile = (CommonsMultipartFile) headIconFile;
            DiskFileItem fileItem = (DiskFileItem) cFile.getFileItem();
            String result = HttpUtils.sendPostFile(DictionaryHelper.getInstance().getDicDisplay("fileServer", "1") + "/upload",
                    fileItem.getInputStream());
            JSONObject jsonObject = JSONObject.parseObject(result);
            int resCode = jsonObject.getIntValue("resCode");
            if(ExceptionState.SUCCESS != resCode) {
                throw new BusinessException("上传文件失败");
            }
            String filePath = jsonObject.getJSONObject("resultList").getString("url");
            appMemberService.updateUserPic(sysId, filePath);
            return toJsonErrorData(ExceptionState.SUCCESS, filePath);
        } catch (Exception e) {
            e.printStackTrace();
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "保存失败");
        }

    }

    /**
     * 个人信息修改
     */
    @ResponseBody
    @RequestMapping(value = "/edit")
    public String memberEdit(HttpServletRequest request, TMember member) {
        logger.info("app/member/edit");
        try {
            Integer uid = (Integer) request.getSession().getAttribute(AppWxInterceptor.WX_USER_ID);
            if (uid == null) {
                return toJsonErrorData(ExceptionState.SESSION_EXCEPTION, "请登录后设置个人信息");
            }
            member.setId(uid);
            appMemberService.updateMember(member);
            return toJsonSuccessData();
        } catch (Exception e) {
            e.printStackTrace();
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "保存失败");
        }
    }


    /**
     * 找回密码，返回手机短信吗
     */
    @ResponseBody
    @RequestMapping(value = "/noteCodeSend")
    public String noteCodeSend(HttpServletRequest request, String mobile, String type) {
        logger.info("app/member/noteCodeSend");
        try {
            if(!StringUtil.isEmpty(type)){
                Integer unit_id = (Integer) request.getSession().getAttribute(AppWxInterceptor.WX_USER_UNIT_ID);
                Map<String, Object> map = appMemberService.getUserByMobile(mobile, unit_id);
                if("register".equals(type)){
                    if(map != null){
                        return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "该手机号已被使用");
                    }
                }else if("forget".equals(type)){
                    if(map == null){
                        return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "该手机号不存在");
                    }
                }
            }
            String noteCode = NoteSendUtil.getRandNum(6);
            logger.info(mobile + ":" + noteCode);
            Long noteCodeTime = (Long) request.getSession().getAttribute("noteCodeTime");
            Long timeNow = (new Date()).getTime();
            if (noteCodeTime != null && (timeNow - noteCodeTime) / 1000 < 60) {
                return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "请勿在60秒内重复发送短信");
            }
            if (NoteSendUtil.verifyNote(mobile, noteCode)) {
                request.getSession().setAttribute("noteCode", noteCode);
                request.getSession().setAttribute("noteCodeMobile", mobile);
                request.getSession().setAttribute("noteCodeTime", (new Date()).getTime());
                return toJsonSuccessData();
            } else {
                return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "请验证您的手机是否正确");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "系统异常");
        }
    }

    /**
     * 修改密码
     */
    @ResponseBody
    @RequestMapping(value = "/pwdEdit")
    public String pwdEdit(HttpServletRequest request, String mobile, String pwdNew, String verifyCode) {
        logger.info("app/member/pwdEdit");
        try {
            String noteCode = (String) request.getSession().getAttribute("noteCode");
            String noteCodeMobile = (String) request.getSession().getAttribute("noteCodeMobile");
            if (noteCode == null || ("").equals(noteCode)) {
                return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "短信验证码错误");
            } else {
                if (noteCode.equals(verifyCode) && mobile.equals(noteCodeMobile)) {
                    Integer unit_id = (Integer) request.getSession().getAttribute(AppWxInterceptor.WX_USER_UNIT_ID);
                    Map<String, Object> map = appMemberService.getUserByMobile(mobile, unit_id);
                    if (map == null) {
                        return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "用户不存在");
                    }
                    appMemberService.updatePsw(mobile, unit_id, StringUtil.MD5(pwdNew));
                    return toJsonSuccessData();
                } else {
                    return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "短信验证码错误");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "查找出错");
        }
    }


    /**
     * 单篇阅读列表
     * @param pageBean
     * @param request
     * @return
     */
    @RequestMapping(value = "singleList")
    @ResponseBody
    public String singleList(PageBean pageBean, HttpServletRequest request) {
        logger.info("app/member/commentList");
        Integer uid = (Integer) request.getSession().getAttribute(AppWxInterceptor.WX_USER_ID);
        Integer root_unit_id = (Integer) request.getSession().getAttribute(AppWxInterceptor.WX_USER_ROOT_UNIT_ID);
        if (uid == null) {
            return toJsonErrorData(ExceptionState.SESSION_EXCEPTION, "请登录后查看个人单篇");
        } else {
            return toJsonListData(appInformationService.singleList(pageBean, uid, root_unit_id));
        }
    }

    /**
     * 个人收藏列表
     * @param pageBean
     * @param request
     * @return
     */
    @RequestMapping(value = "collectList")
    @ResponseBody
    public String collectList(PageBean pageBean, HttpServletRequest request) {
        logger.info("app/member/commentList");
        Integer uid = (Integer) request.getSession().getAttribute(AppWxInterceptor.WX_USER_ID);
        Integer root_unit_id = (Integer) request.getSession().getAttribute(AppWxInterceptor.WX_USER_ROOT_UNIT_ID);
        if (uid == null) {
            return toJsonErrorData(ExceptionState.SESSION_EXCEPTION, "请登录后查看个人收藏");
        } else {
            return toJsonListData(appInformationService.collectList(pageBean, uid, root_unit_id));
        }
    }

    /**
     * 个人历史列表
     * @param pageBean
     * @param request
     * @return
     */
    @RequestMapping(value = "historyList")
    @ResponseBody
    public String historyList(PageBean pageBean, HttpServletRequest request) {
        logger.info("app/member/commentList");
        Integer uid = (Integer) request.getSession().getAttribute(AppWxInterceptor.WX_USER_ID);
        Integer root_unit_id = (Integer) request.getSession().getAttribute(AppWxInterceptor.WX_USER_ROOT_UNIT_ID);
        if (uid == null) {
            return toJsonErrorData(ExceptionState.SESSION_EXCEPTION, "请登录后查看历史记录");
        } else {
            return toJsonListData(appInformationService.historyList(pageBean, uid, root_unit_id));
        }
    }

    /**
     * 我的通知-评论
     *
     * @return
     */
    @RequestMapping(value = "commentList")
    @ResponseBody
    public String commentList(PageBean pageBean, HttpServletRequest request, MemberComment memberComment) {
        logger.info("app/member/commentList");
        Integer uid = (Integer) request.getSession().getAttribute(AppWxInterceptor.WX_USER_ID);
        if (uid == null) {
            return toJsonErrorData(ExceptionState.SESSION_EXCEPTION, "请登录后查看个人评论");
        } else {
            memberComment.setMember_id(uid);
            return toJsonListData(appMemberCommentService.commentList(pageBean, memberComment));
        }
    }


    /**
     * 通知列表
     */
    @RequestMapping(value = "/notices")
    @ResponseBody
    public String notices(HttpServletRequest request, PageBean pageBean, MemberNotice memberNotice) {
        logger.info("app/member/notices");
        Integer uid = (Integer) request.getSession().getAttribute(AppWxInterceptor.WX_USER_ID);
        if (uid == null) {
            return toJsonErrorData(ExceptionState.SESSION_EXCEPTION, "请登录后查看通知列表");
        }
        memberNotice.setMember_id(uid);
        return toJsonListData(appMemberNoticeService.list(pageBean, memberNotice));
    }

    /**
     * 通知详情
     */
    @ResponseBody
    @RequestMapping(value = "notice")
    public String notice(HttpServletRequest request, Integer id) {
        logger.info("/app/member/notice");
        Integer uid = (Integer) request.getSession().getAttribute(AppWxInterceptor.WX_USER_ID);
        try {
            if (uid == null) {
                return toJsonErrorData(ExceptionState.SESSION_EXCEPTION, "用户未登录");
            } else {
                Map<String,Object> notice = appMemberNoticeService.get(id);
                appMemberNoticeService.readUpdate(id, uid);
                return toJsonSuccessData(notice);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "获取通知失败");
        }
    }

    /**
     * 全部标签
     */
    @ResponseBody
    @RequestMapping(value = "labelGet")
    public String labelGet(HttpServletRequest request) {
        logger.info("/app/member/labelGet");
        try {
            Integer unit_id = (Integer) request.getSession().getAttribute(AppWxInterceptor.WX_USER_ROOT_UNIT_ID);
            return toJsonSuccessData(appMemberService.labelGet(unit_id));
        } catch (Exception e) {
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "获取标签失败");
        }
    }

    /**
     * 标签
     */
    @ResponseBody
    @RequestMapping(value = "userLabelGet")
    public String userLabelGet(HttpServletRequest request) {
        logger.info("/app/member/labelGet");
        try {
            Integer id = (Integer) request.getSession().getAttribute(AppWxInterceptor.WX_USER_ID);
            if (id == null) {
                return toJsonErrorData(ExceptionState.SESSION_EXCEPTION, "请登录后重试");
            }
            Map<String, Object> member = appMemberService.getMemberById(id);
            Integer unit_id = (Integer) request.getSession().getAttribute(AppWxInterceptor.WX_USER_ROOT_UNIT_ID);
            List<Map<String, Object>> labelList = appMemberService.labelGet(unit_id);
            if (member != null && member.get("tags") != null) {
                String[] userTags = member.get("tags").toString().split(",");
                if (labelList != null && labelList.size() > 0 && userTags != null && userTags.length > 0) {
                    for (int i = 0; i < labelList.size(); i++) {
                        for (int j = 0; j < userTags.length; j++) {
                            if (labelList.get(i).get("id").toString().equals(userTags[j])) {
                                labelList.get(i).put("isUser", "1");
                            }
                        }
                    }
                }
            }
            return toJsonSuccessData(labelList);
        } catch (Exception e) {
            e.printStackTrace();
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "获取标签失败");
        }
    }

    /**
     * 收藏
     * @param request
     * @param vipCollection
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/collect")
    public String collect(HttpServletRequest request, MemberCollection vipCollection){
        logger.info("/app/member/collect");
        Integer uid = (Integer) request.getSession().getAttribute(AppWxInterceptor.WX_USER_ID);
        try {
            if (uid == null) {
                return toJsonErrorData(ExceptionState.SESSION_EXCEPTION, "请登录后重试");
            } else {
                boolean isCollected = appMemberCollectionService.isCollected(uid, vipCollection.getBusiness_id(), vipCollection.getBusiness_type());
                if(isCollected){
                    return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION,"您已收藏此信息");
                }else {
                    vipCollection.setMember_id(uid);
                    vipCollection.setCreate_time(new Date());
                    appMemberCollectionService.save(vipCollection);
                    return toJsonSuccessData();
                }
            }

        }catch (Exception e){
            e.printStackTrace();
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "收藏失败");
        }
    }

    /**
     * 取消收藏
     * @param request
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/cancel")
    public String cancel(HttpServletRequest request, Integer id){
        Integer uid = (Integer) request.getSession().getAttribute(AppWxInterceptor.WX_USER_ID);
        try {
            if (uid == null) {
                return toJsonErrorData(ExceptionState.SESSION_EXCEPTION, "请登录后重试");
            } else {
                appMemberCollectionService.del(id);
                return toJsonSuccessData();
            }

        }catch (Exception e){
            e.printStackTrace();
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "取消收藏失败");
        }
    }

    /**
     * 删除历史记录
     * @param request
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/historyDel")
    public String historyDel(HttpServletRequest request, Integer id){
        Integer uid = (Integer) request.getSession().getAttribute(AppWxInterceptor.WX_USER_ID);
        try {
            if (uid == null) {
                return toJsonErrorData(ExceptionState.SESSION_EXCEPTION, "请登录后重试");
            } else {
                appMemberTrackService.del(id);
                return toJsonSuccessData();
            }
        }catch (Exception e){
            e.printStackTrace();
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "删除失败");
        }
    }

    /**
     * 关注
     * @param request
     * @param unit_id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/focus")
    public String focus(HttpServletRequest request, Integer unit_id) {
        Integer uid = (Integer) request.getSession().getAttribute(AppWxInterceptor.WX_USER_ID);
        try {
            if (uid == null) {
                return toJsonErrorData(ExceptionState.SESSION_EXCEPTION, "请登录后重试");
            } else {
                int is_focus = appMemberFocusService.isFocus(unit_id, uid);
                if(is_focus == GlobalValue.YES){
                    appMemberFocusService.del(unit_id, uid);
                    return toJsonSuccessData();
                }else{
                    MemberFocus memberFocus = new MemberFocus();
                    memberFocus.setMember_id(uid);
                    memberFocus.setUnit_id(unit_id);
                    appMemberFocusService.save(memberFocus);
                    return toJsonSuccessData();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "操作失败");
        }
    }

    /**
     * 关注列表
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/focusList")
    public String focusList(HttpServletRequest request,PageBean pageBean) {
        Integer uid = (Integer) request.getSession().getAttribute(AppWxInterceptor.WX_USER_ID);
        try {
            if (uid == null) {
                return toJsonErrorData(ExceptionState.SESSION_EXCEPTION, "请登录后重试");
            } else {
                return toJsonListData(appMemberService.focusList(pageBean,uid));
            }
        }catch (Exception e){
            e.printStackTrace();
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "关注失败");
        }
    }

}
